package darkwindclient.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

/**
 * @author Jacob Ferm 
 */
public class MainFrame extends JPanel {
	private JScrollPane top;
	private JScrollPane bot;
	private JScrollBar topScroll;
	private boolean scroll;
	private MainFrame rawr = this;

	public MainFrame(TextField text, TextField log) {
		super();
		scroll = false;
		setSize(700, 750);

		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		this.setBackground(Color.BLACK);
		this.setOpaque(true);

		bot = new JScrollPane(text,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		bot.getVerticalScrollBar().addAdjustmentListener(
				new AdjustmentListener() {
					public void adjustmentValueChanged(AdjustmentEvent e) {
						e.getAdjustable().setValue(
								e.getAdjustable().getMaximum());
					}
				});
		bot.setVisible(true);

		top = new JScrollPane(log,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		top.setVisible(false);
		topScroll = top.getVerticalScrollBar();
		topScroll.addAdjustmentListener(new AdjustmentListener() {
			public void adjustmentValueChanged(AdjustmentEvent e) {
				if (!scroll) {
					e.getAdjustable().setValue(e.getAdjustable().getMaximum());
				}
			}
		});

		bot.setMinimumSize(new Dimension(700, 200));
		bot.setPreferredSize(new Dimension(getWidth(), getHeight()));
		top.setMinimumSize(new Dimension(700, 550));
		top.setPreferredSize(new Dimension(700, 550));
		add(top);
		add(bot);

		ScrollListener sl = new ScrollListener();
		bot.addMouseWheelListener(sl);
		top.addMouseWheelListener(sl);
	}

	/**
	 * @author Jacob Ferm
	 */
	private class ScrollListener implements MouseWheelListener {

		@Override
		public void mouseWheelMoved(MouseWheelEvent arg0) {
			int notches = arg0.getWheelRotation();
			if (!scroll && notches < 0) {
				top.setVisible(true);
				scroll = true;
				rawr.revalidate();
				topScroll.setValue(topScroll.getMaximum()
						- bot.getVerticalScrollBar().getVisibleAmount());
			} else if (topScroll.getValue() == topScroll.getMaximum()
					- topScroll.getVisibleAmount()) {
				top.setVisible(false);
				scroll = false;
				rawr.revalidate();
			} else {
			}
		}
	}

}
